package com.sychip.fhc.app.wsn.screen.components

import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.TransformOrigin
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.sychip.fhc.app.wsn.screen.MapDeviceDto
import kotlinx.coroutines.delay
import timber.log.Timber
import kotlin.math.roundToInt


@Composable
fun MovableDevice(
    device: MapDeviceDto,
    containerSize: IntSize,
    selfSize: DpSize,
    selfOffset: Offset,
    onDragMove: (MapDeviceDto, Float, Float) -> Unit,
    onDragEnd: (MapDeviceDto, Float, Float) -> Unit,
    onGloballyPositioned: (MapDeviceDto, Offset) -> Unit,
    onClick: (MapDeviceDto) -> Unit = {},
) {

    var offset by remember { mutableStateOf(selfOffset) }

    // 立即更新的回调引用
    val currentCallbacks = remember(device) {
        object {
            val onClick = onClick
            val onDragMove = onDragMove
            val onDragEnd = onDragEnd
            val onGloballyPositioned = onGloballyPositioned
        }
    }

    // 边界计算（优化版）
    val maxOffset = with(LocalDensity.current) {
        Offset(
            containerSize.width - selfSize.width.toPx(),
            containerSize.height - selfSize.height.toPx()
        )
    }
    // 心跳动画
    val heartbeatAnimation = remember { Animatable(1f) }
    LaunchedEffect(device.rssiUpdated) {
        if (device.rssiUpdated) {
            // 运行1.5秒的心跳动画 (3次跳动，每次500ms)
            repeat(2) {
                heartbeatAnimation.animateTo(
                    targetValue = 0.75f,
                    animationSpec = tween(300)
                )
                delay(50)
                heartbeatAnimation.animateTo(
                    targetValue = 1f,
                    animationSpec = tween(300)
                )

            }
        }
    }

    // 颜色动画 - 从设备原始颜色渐变到黑色背景和白色文字
    val bgAnimation = remember { Animatable(0f) }
    
    // 控制是否显示动画颜色的状态
    var showAnimatedColors by remember { mutableStateOf(false) }
    
    // 当设备的rssi更新时，触发动画
    LaunchedEffect(device.devId, device.rssiUpdated) {
//        Timber.i("MovableDevice>>>>>       ${device.devId}    ${device.rssiUpdated}")
        if (device.rssiUpdated) {
            showAnimatedColors = true
            repeat(2) {
                bgAnimation.animateTo(
                    targetValue = 1f,
                    animationSpec = tween(300)
                )
                delay(50)
                bgAnimation.animateTo(
                    targetValue = 0f,
                    animationSpec = tween(300)
                )
            }
            // 动画结束后重置状态，使用设备原始颜色
            showAnimatedColors = false
        }else{
            showAnimatedColors = false
        }
    }

    Box(
        modifier = Modifier
            .offset { IntOffset(offset.x.roundToInt(), offset.y.roundToInt()) }
            .graphicsLayer {
                scaleX = if(device.rssiUpdated) heartbeatAnimation.value else 1f
                scaleY = if(device.rssiUpdated) heartbeatAnimation.value else 1f
                transformOrigin = TransformOrigin.Center
                clip = false
            }
            .size(selfSize.width, selfSize.height)
            .clip(RoundedCornerShape(6.dp))
            .background(
                if(device.isNoUpdate60s){
//                    NoUpdateBgColor
                    device.bgColor.copy(alpha = if(device.unHighlight) 0.3f else 1f)
                }else{
//                    if (showAnimatedColors) {
//                        // 根据动画进度在设备背景色和黑色之间插值
//                        lerpColor(device.bgColor, Color.Black, bgAnimation.value)
//                            .copy(alpha = if(device.unHighlight) 0.3f else 1f)
//                    } else {
                    device.bgColor.copy(alpha = if(device.unHighlight) 0.3f else 1f)
//                    }
                }
            )
            .clickable { currentCallbacks.onClick(device) }
            .pointerInput(device.devId, containerSize) {
                detectDragGestures(
                    onDrag = { change, dragAmount ->
                        try {
                            change.consume()
                            val newOffset = Offset(
                                (offset.x + dragAmount.x).coerceIn(0f, maxOffset.x),
                                (offset.y + dragAmount.y).coerceIn(0f, maxOffset.y)
                            )
                            offset = newOffset
                            // 同步调用确保即时响应
                            currentCallbacks.onDragMove(device, newOffset.x, newOffset.y)
                        }catch (e: Exception){
                            e.printStackTrace()
                            Timber.e(e.toString())
                        }
                    },
                    onDragEnd = {
                        currentCallbacks.onDragEnd(device, offset.x, offset.y)
                    }
                )
            }
            .onGloballyPositioned {
                currentCallbacks.onGloballyPositioned(device, offset)
            }
    ) {
        Text(
            text =  device.devId,
            modifier = Modifier.fillMaxSize().wrapContentHeight(Alignment.CenterVertically), // 垂
            color = if(device.isNoUpdate60s){
//                NoUpdateFrColor
                device.txtColor.copy(alpha = if(device.unHighlight) 0.3f else 1f)
            }else{
//                if (showAnimatedColors) {
//                    Color.White.copy(alpha = if(device.unHighlight) 0.3f else 1f)
//                } else {
                    device.txtColor.copy(alpha = if(device.unHighlight) 0.3f else 1f)
//                }
            },
            fontSize = 16.sp,
            fontWeight = FontWeight.Bold,
            textAlign = TextAlign.Center,
            style = MaterialTheme.typography.titleLarge
        )
    }
}

/**
 * 在两个颜色之间进行线性插值
 *
 * @param startColor 起始颜色
 * @param endColor 结束颜色
 * @param fraction 插值因子，范围为0f到1f
 * @return 插值后的颜色
 */
fun lerpColor(startColor: Color, endColor: Color, fraction: Float): Color {
    val red = startColor.red + fraction * (endColor.red - startColor.red)
    val green = startColor.green + fraction * (endColor.green - startColor.green)
    val blue = startColor.blue + fraction * (endColor.blue - startColor.blue)
    val alpha = startColor.alpha + fraction * (endColor.alpha - startColor.alpha)
    return Color(red, green, blue, alpha)
}